package org.algorithm.熊猫.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;


/**
 * @Date 2022/2/24
 * @Desc {https://leetcode-cn.com/problems/add-two-numbers/}
 */
public class 链表相加 {

    @Test
    public void test() {
        ListNode build1 = ListNode.build(1, 2, 3, 4);
        ListNode build = ListNode.build(1, 2, 3, 4, 5);
        ListNode node = addTwoNumbers(build1, build);
        System.out.println( ListNode.print(node));
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode head = new ListNode();

        boolean flag = false;
        ListNode curtNode = head;
        while (l1 != null || l2 != null) {
            curtNode.next = new ListNode();
            int int1 = 0;
            int int2 = 0;
            if (l1 != null) {
                int1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                int2 = l2.val;
                l2 = l2.next;
            }
            int count = int1 + int2;
            if (flag) {
                count++;
                flag = false;
            }
            if (count >= 10) {
                flag = true;
                count = count - 10;
            }
            curtNode.next.val = count;
            curtNode = curtNode.next;
        }

        if(flag){
            curtNode.next = new ListNode();
            curtNode.next.val=1;
        }

        return head.next;
    }
}
